package com.c.common.service.impl;

import com.c.common.service.RedisService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author bysun
 */
@Service
public class RedisServiceImpl implements RedisService {

    /**
     * 默认过期时长，单位：秒
     */
    public static final long DEFAULT_EXPIRE = 60 * 60 * 2;

    /**
     * 不设置过期时长
     */
    public static final long NOT_EXPIRE = -1;

    @Autowired
    ValueOperations valueOperations;

    @Autowired
    RedisTemplate<String, String> redisTemplate;

    @Override
    public void set(String key, String value) {
        valueOperations.set(key, value);
    }

    @Override
    public void set(String key, String value, Long time) {
        set(key, value, time, TimeUnit.SECONDS);
    }

    @Override
    public void set(String key, String value, Long time, TimeUnit timeUnit) {
        valueOperations.set(key, value, time, timeUnit);
    }

    @Override
    public String get(String key) {
        return String.valueOf(valueOperations.get(key));
    }

    @Override
    public boolean exist(String key) {
        if (StringUtils.isBlank(key)) {
            return false;
        }
        return redisTemplate.hasKey(key);
    }

    @Override
    public void del(String key) {
        redisTemplate.delete(key);
    }

    @Override
    public void rename(String oldKey, String newKey) {
        redisTemplate.rename(oldKey, newKey);
    }

}
